package com.wgn.reportquery.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.TransformerException;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.sun.org.apache.xpath.internal.XPathAPI;
import com.wgn.reportquery.cons.Const;
import com.wgn.reportquery.dao.QueryDaoImple;
import com.wgn.reportquery.model.Card;
import com.wgn.reportquery.model.Query;
import com.wgn.reportquery.model.Report;
import com.wgn.reportquery.model.User_SK;
import com.wgn.reportquery.rj.model.PhUserCard;
import com.wgn.reportquery.rj.model.PhUsers;
import com.wgn.reportquery.rj.model.RJUser;
import com.wgn.reportquery.utils.Importer;
import com.wgn.reportquery.utils.ReportUtils;

public class QueryHttpClient {
	String username;
	String passwd;

	public QueryHttpClient(String username, String passwd) throws Exception {
		this.username = username;
		this.passwd = passwd;
		// 初始化就登陆
		for (int i = 0; i < Const.maxTry; i++) {
			boolean ok = logSk();
			if (ok) {
				System.out.println(username + "登陆成功");
				return;
			}
		}
		System.out.println(username + "登陆失败");
		throw new Exception(username + "登陆失败");
	}

	public QueryHttpClient(String username, String passwd, String type,
			String regname) throws Exception {
		this.username = username;
		this.passwd = passwd;
		// 初始化就登陆
		for (int i = 0; i < Const.maxTry; i++) {
			RJUser user = logRenji();
			if (null != user) {
				if (user.isErrmsg())// 仁济的用户名密码输入错误!
				{

					throw new Exception(user.getErrMsg());

				}
				System.out.println(username + "登陆仁济成功");
				// 解析返回字符串，入库
				QueryDaoImple dao = new QueryDaoImple();
				String sql = "UPDATE G_USER SET G_USER.`RJUSERNAME`=? ,G_USER.`RJPASSWD`=? WHERE G_USER.`USERNAME`=?";
				List<String> para = new ArrayList<String>();
				para.add(username);
				para.add(passwd);
				para.add(regname);
				dao.update(sql, para);

				sql = "insert into RJCARD (CARDNO,USERNAME,CARDTYPE) values(?,?,?)";
				String ifexit = "select * from RJCARD where CARDNO=? and USERNAME=?";// 看看是否存在老卡
				List<PhUserCard> ulist = user.getPhUsers().getPhUserCard();
				for (PhUserCard card : ulist) {

					para.clear();// 添加医保卡
					String card_Num = card.getCard_Num();
					para.add(card_Num);
					para.add(regname);
					if (dao.ifExist(ifexit, para))
						continue;
					para.add("1");
					dao.update(sql, para);
				}
				return;
			}
		}
		System.out.println(username + "登陆仁济失败");
	}

	public QueryHttpClient() {
		// TODO Auto-generated constructor stub
		if (null == httpclient)
			httpclient = HttpClients.createDefault();
	}

	public QueryHttpClient(String username2) {
		// TODO Auto-generated constructor stub
		if (null == httpclient)
			httpclient = HttpClients.createDefault();
		this.username = username2;
	}

	/**
	 * 登陆申康个人中心
	 */
	public boolean logSk(String username, String passwd) {
		// 创建默认的httpClient实例.
		if (null == httpclient)
			httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost();
		// 创建参数队列

		// hospital_id=42502657201&hospital_name=%E4%BB%81%E6%B5%8E%E5%8C%BB%E9%99%A2%E4%B8%9C%E9%99%A2&start_time
		// =2017-04-01&end_time=2017-05-08&cardId=K09021348&cardType=SocialSecurity
		// 获取申康用户名密码
		QueryDaoImple dao = new QueryDaoImple();
		User_SK user = dao.getSkUser(username, passwd);
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("username", user.getName_sk()));
		formparams.add(new BasicNameValuePair("password", user.getPasswd_sk()));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("-----------log sk---" + username + ","
							+ passwd);
					String message = EntityUtils.toString(entity, "UTF-8");
					System.out.println("Response content: " + message);
					if (message.indexOf("失败") > 0)
						return false;
					System.out
							.println("--------------log ok------------------------");
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return true;
		}
	}

	/**
	 * 登陆申康
	 */
	public boolean logSk() {
		// 创建默认的httpClient实例.
		if (null == httpclient)
			httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(Const.SK_LOG_URL);
		// 创建参数队列

		// hospital_id=42502657201&hospital_name=%E4%BB%81%E6%B5%8E%E5%8C%BB%E9%99%A2%E4%B8%9C%E9%99%A2&start_time
		// =2017-04-01&end_time=2017-05-08&cardId=K09021348&cardType=SocialSecurity
		// 获取申康用户名密码
		QueryDaoImple dao = new QueryDaoImple();
		User_SK user = dao.getSkUser(username, passwd);
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("username", user.getName_sk()));
		formparams.add(new BasicNameValuePair("password", user.getPasswd_sk()));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("-----------log sk---" + username + ","
							+ passwd);
					String message = EntityUtils.toString(entity, "UTF-8");
					System.out.println("Response content: " + message);
					if (message.indexOf("失败") > 0)
						return false;
					System.out
							.println("--------------log ok------------------------");
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return true;
		}
	}

	public String querySkURls(Query q) {
		String cardId = q.getCardId();
		String end_time = q.getEnd_time();
		String hospital_id = q.getHospital_id();
		String start_time = q.getStart_time();

		// cardType和hospitalName要从数据库取
		QueryDaoImple dao = new QueryDaoImple();

		dao.updateQuery(q);// 获取医保卡类型
		String hospital_name = q.getHospital_name();
		String cardType = q.getCardType();
		// 创建httppost
		HttpPost httppost = new HttpPost(Const.SK_LOG_URL);
		// 创建参数队列
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		UrlEncodedFormEntity uefEntity;

		try {

			// 查询***********************
			httppost = new HttpPost(Const.SK_REPORT_QUERY_URL);
			formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("cardId", cardId));
			formparams.add(new BasicNameValuePair("cardType", cardType));
			formparams.add(new BasicNameValuePair("end_time", end_time));
			if (null != hospital_id) {
				formparams.add(new BasicNameValuePair("hospital_id",
						hospital_id));
				formparams.add(new BasicNameValuePair("hospital_name",
						hospital_name));
			}
			formparams.add(new BasicNameValuePair("start_time", start_time));
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing query " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				System.out
						.println("-------------query-----sktable--------------------");
				String queryTable = EntityUtils.toString(entity, "UTF-8")
						.replaceAll("href", "ohref");
				;
				System.out.println(queryTable);

				System.out
						.println("------------------------query end--------------");
				return queryTable;

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 登陆后查询,返回一个html list = Importer.match(queryTable, Const.pattern_report);
	 */
	/*
	 * public String querySk(Query q) { String cardId = q.getCardId(); String
	 * end_time = q.getEnd_time(); String hospital_id = q.getHospital_id();
	 * String start_time = q.getStart_time();
	 * 
	 * // cardType和hospitalName要从数据库取 QueryDaoImple dao = new QueryDaoImple();
	 * if (q.getHospital_id() != null) dao.updateQuery(q); String hospital_name
	 * = q.getHospital_name(); String cardType = q.getCardType();
	 * 
	 * // 创建httppost HttpPost httppost = new HttpPost(Const.SK_LOG_URL); //
	 * 创建参数队列 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	 * 
	 * UrlEncodedFormEntity uefEntity;
	 * 
	 * try {
	 * 
	 * // 查询*********************** httppost = new
	 * HttpPost(Const.SK_REPORT_QUERY_URL); formparams = new
	 * ArrayList<NameValuePair>(); formparams.add(new
	 * BasicNameValuePair("cardId", cardId)); formparams.add(new
	 * BasicNameValuePair("cardType", cardType)); formparams.add(new
	 * BasicNameValuePair("end_time", end_time)); if (null != hospital_id) {
	 * formparams.add(new BasicNameValuePair("hospital_id", hospital_id));// wgn
	 * formparams.add(new BasicNameValuePair("hospital_name", hospital_name)); }
	 * formparams.add(new BasicNameValuePair("start_time", start_time));
	 * uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
	 * httppost.setEntity(uefEntity); System.out.println("executing query " +
	 * httppost.getURI()); CloseableHttpResponse response =
	 * httpclient.execute(httppost); HttpEntity entity = response.getEntity();
	 * if (entity != null) { System.out
	 * .println("-------------query-------------------------"); String
	 * queryTable = EntityUtils.toString(entity, "UTF-8") .replaceAll("href",
	 * "ohref"); ; System.out.println(queryTable);
	 * 
	 * System.out .println("------------------------query end--------------");
	 * return queryTable; } } catch (Exception e) { e.printStackTrace(); }
	 * return ""; }
	 */

	CloseableHttpClient httpclient;

	public InputStream getImgSk(String wholeurl) {
		// 创建默认的httpClient实例.

		InputStream in = null;

		HttpEntity entity;

		{

			System.out.println(wholeurl);
			HttpGet httpget = new HttpGet(wholeurl);
			try {
				System.out
						.println("------------------------get start--------------");
				CloseableHttpResponse response = httpclient.execute(httpget);
				entity = response.getEntity();

				// new一个URL对象

				in = entity.getContent();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return in;
	}

	/**
	 * 无参数,根据申康查到的url列表，获取html String
	 */
	public String getHtmlSk(String wholeurl) {
		// 创建默认的httpClient实例.

		String html = "";

		HttpEntity entity;

		{

			System.out.println(wholeurl);
			HttpGet httpget = new HttpGet(wholeurl);
			try {
				System.out
						.println("------------------------get start--------------");
				CloseableHttpResponse response = httpclient.execute(httpget);
				entity = response.getEntity();
				html = EntityUtils.toString(entity, "UTF-8");
				System.out.println(html);
				System.out.println("------------------------get end--------");
				response.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return html;

	}

	/**
	 * 无参数,根据申康查到的url列表，获取html String
	 */
	public List<Card> getSkCards(String wholeurl) {
		// 创建默认的httpClient实例.
		List<Card> cards = null;
		HttpEntity entity;

		{

			System.out.println(wholeurl);
			HttpGet httpget = new HttpGet(wholeurl);
			try {
				System.out
						.println("------------------------get start--------------");
				CloseableHttpResponse response = httpclient.execute(httpget);
				entity = response.getEntity();
				// System.out.println(EntityUtils.toString(entity, "utf-8"));
				InputStream ins = entity.getContent();
				// 创建一个解析器
				DOMParser parser = new DOMParser();
				// 解析HTML文件
				parser.parse("file:///d:/tmp/2.html");
				// 获取解析后的DOM树
				Document document = parser.getDocument();

				// 通过getElementsByTagName获取Node
				NodeList nodeList = document.getElementsByTagName("td");
				int jiange = 9;
				for (int i = 0; i < nodeList.getLength(); i = i + jiange) {
					System.out.println("*新的卡**");
					if (null == cards)
						cards = new ArrayList<Card>();
					Element cardtype = (Element) nodeList.item(i + 1);
					Element cardnum = (Element) nodeList.item(i + 2);

					// System.out.print(e.getAttribute("href") + "\t");
					System.out.println("--卡类型--"
							+ cardtype.getTextContent().trim() + "--");
					System.out.println("--卡号-"
							+ cardnum.getTextContent().trim() + "--");
					Card c = new Card();
					c.setNo(cardnum.getTextContent().trim());
					c.setType(cardtype.getTextContent().trim());
					cards.add(c);
				}
				System.out.println("------------------------get end--------");
				response.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return cards;
	}

	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public void logQuerySave() {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(Const.SK_LOG_URL);
		// 创建参数队列

		// hospital_id=42502657201&hospital_name=%E4%BB%81%E6%B5%8E%E5%8C%BB%E9%99%A2%E4%B8%9C%E9%99%A2&start_time
		// =2017-04-01&end_time=2017-05-08&cardId=K09021348&cardType=SocialSecurity
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("username", "squail83"));
		formparams.add(new BasicNameValuePair("password", "Aa888888"));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out
							.println("--------------------------------------");
					System.out.println("Response content: "
							+ EntityUtils.toString(entity, "UTF-8"));
					System.out
							.println("--------------------------------------");
					// 查询***********************
					httppost = new HttpPost(Const.SK_REPORT_QUERY_URL);
					formparams = new ArrayList<NameValuePair>();
					formparams
							.add(new BasicNameValuePair("cardId", "K09021348"));
					formparams.add(new BasicNameValuePair("cardType",
							"SocialSecurity"));
					formparams.add(new BasicNameValuePair("end_time",
							"2017-05-08"));
					formparams.add(new BasicNameValuePair("hospital_id",
							"42502657201"));
					formparams.add(new BasicNameValuePair("hospital_name",
							"仁济医院东院"));
					formparams.add(new BasicNameValuePair("start_time",
							"2017-04-15"));
					uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
					httppost.setEntity(uefEntity);
					System.out.println("executing query " + httppost.getURI());
					response = httpclient.execute(httppost);
					entity = response.getEntity();
					if (entity != null) {
						System.out
								.println("-------------query-------------------------");
						String queryTable = EntityUtils.toString(entity,
								"UTF-8");
						List<String> list = Importer.match(queryTable,
								Const.pattern_report);
						System.out
								.println("------------------------query size:"
										+ list.toString() + "--------------");
						for (String url : list) {
							String wholeurl = Const.SK_REPORT_URL + url;
							System.out.println(wholeurl);
							HttpGet httpget = new HttpGet(wholeurl);
							response = httpclient.execute(httpget);
							entity = response.getEntity();
							String queryReport = EntityUtils.toString(entity,
									"UTF-8");
							System.out.println(queryReport);
						}
						System.out
								.println("------------------------query end--------------");
					}
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String gethostpitalhtml() throws Exception {
		// TODO Auto-generated method stub
		QueryHttpClient client = new QueryHttpClient(Const.adminname,
				Const.adminpasswd);
		String html = client.getHtmlSk(Const.SK_HOSTPITAL_URL);
		client.close();
		return html;
	}

	public void close() {
		// TODO Auto-generated method stub
		try {
			this.httpclient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public HttpPost getPost(String url) {
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httppost.setHeader("Connection", "Keep-Alive");
		return httppost;
	}

	public String post(HttpPost httppost, List<NameValuePair> formparams) {
		// TODO Auto-generated method stub

		// 创建默认的httpClient实例.
		if (null == httpclient)
			httpclient = HttpClients.createDefault();
		// 创建httppost

		// 创建参数队列

		// //
		// hospital_id=42502657201&hospital_name=%E4%BB%81%E6%B5%8E%E5%8C%BB%E9%99%A2%E4%B8%9C%E9%99%A2&start_time
		// //
		// =2017-04-01&end_time=2017-05-08&cardId=K09021348&cardType=SocialSecurity
		// //获取仁济用户名密码
		// QueryDaoImple dao = new QueryDaoImple();
		// User_SK user=dao.getRjUser(username,passwd);
		String message = "";
		try {

			UrlEncodedFormEntity uefEntity;
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("-----------post --start-");
					StringBuilder sBuilder = new StringBuilder();
					InputStreamReader isr = new InputStreamReader(
							entity.getContent(), "UTF-8");
					BufferedReader bReader = new BufferedReader(isr);
					String s = "";
					for (s = bReader.readLine(); s != null; s = bReader
							.readLine()) {
						sBuilder.append(s);
					}
					message = sBuilder.toString();// EntityUtils.toString(entity,
													// "UTF-8");
					System.out.println("Response content: " + message);
					System.out
							.println("--------------post  end------------------------");
					return message;

				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return message;
		}

	}

	public RJUser logRenji() {
		RJUser user = null;
		HttpPost httppost = getPost(Const.RJ_URL);
		// //获取仁济用户名密码
		// QueryDaoImple dao = new QueryDaoImple();
		// User_SK user=dao.getRjUser(username,passwd);

		String gson = Const.RJ_LOGJSON.replace("#pwd", passwd).replace(
				"#username", username);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("gson", gson));
		formparams.add(new BasicNameValuePair("type", "6"));
		String json = post(httppost, formparams);
		user = (RJUser) ReportUtils.str2Object(json, RJUser.class);
		return user;
	}

	public String queryRj(String gson) {
		// TODO Auto-generated method stub

		HttpPost httppost = getPost(Const.RJ_URL);
		// //获取仁济用户名密码
		// QueryDaoImple dao = new QueryDaoImple();
		// User_SK user=dao.getRjUser(username,passwd);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("gson", gson));
		formparams.add(new BasicNameValuePair("type",
				Const.RJ_Query_Reports_Type));
		String message = post(httppost, formparams);

		return message;

	}

	public String queryRjReport(String gson) {

		// TODO Auto-generated method stub

		HttpPost httppost = getPost(Const.RJ_URL);
		// //获取仁济用户名密码
		// QueryDaoImple dao = new QueryDaoImple();
		// User_SK user=dao.getRjUser(username,passwd);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("gson", gson));
		formparams.add(new BasicNameValuePair("type",
				Const.RJ_Query_Report_Type));
		String message = post(httppost, formparams);
		return message;

	}

	public static byte[] readInputStream(InputStream inStream) {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		// 创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		// 每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		// 使用一个输入流从buffer里把数据读取出来
		try {
			while ((len = inStream.read(buffer)) != -1) {
				// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
				outStream.write(buffer, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 关闭输入流
		// inStream.close();
		// 把outStream里的数据写入内存
		return outStream.toByteArray();
	}

	public String bindSK(String m, String skuser, String skpasswd,
			String nameNo64, String passwdNo64) {
		try {

			HttpPost httppost = getPost("http://yuyue.shdc.org.cn/loginAction!loginQuick.action");
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();

			formparams.add(new BasicNameValuePair("orderwebUser.userName",
					skuser/* "c3F1YWlsODM%3D" */));
			formparams
					.add(new BasicNameValuePair("userPassword", skpasswd/* "QWE4ODg4ODg%3D" */));
			formparams.add(new BasicNameValuePair("certCode", m));
			post(httppost, formparams);
			List<Card> cards = getSkCards(Const.skcentercardurl);
			if (null == cards || cards.size() == 0)
				return "你未注册医联网或者医联网里面没绑定卡！解决方法见底下的图片";
			// 入库
			QueryDaoImple dao = new QueryDaoImple();
			String sql = "UPDATE G_USER SET G_USER.`SKUSERNAME`=? ,G_USER.`SKPASSWD`=? WHERE G_USER.`USERNAME`=?";
			List<String> para = new ArrayList<String>();
			para.add(nameNo64);
			para.add(passwdNo64);
			para.add(username);
			dao.update(sql, para);// 更新user
			sql = "insert into CARD (CARDNO,USERNAME,CARDTYPE) values(?,?,?)";
			String ifexit = "select * from CARD where CARDNO=? and USERNAME=?";// 看看是否存在老卡

			for (Card card : cards) {

				para.clear();// 添加医保卡
				String card_Num = card.getNo();
				para.add(card_Num);
				para.add(username);
				if (dao.ifExist(ifexit, para))// 有就不添加
					continue;
				para.add(card.getType());// 添加
				dao.update(sql, para);
			}
			return "ok";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
	}
}